package com.itealabs.postjson;

import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;

/**
 * Provide PostJson service.
 * @version $Id: PostJsonService.java 19 2010-05-06 13:50:17Z iteahere $
 * @author itea
 * @date 2010-4-16
 */
public class PostJsonService {

	private JsonRequestWaiter jsonRequestWaiter;
	private ObjectMapper jsonMapper = new ObjectMapper();
	
	public void service(Reader in, Writer out, Map<String, Object> ctx) 
	throws JsonProcessingException, IOException {
		
		JsonRequest jsonReq = buildJsonRequest(jsonMapper.readTree(in), jsonMapper);
		JsonResponse jsonResp = new JsonResponse();
		
		jsonRequestWaiter.service(jsonReq, jsonResp, ctx);
		
		jsonResp.setSeq(jsonReq.getSeq());
		jsonResp.setServerTime(System.currentTimeMillis());
		jsonMapper.writeValue(out, jsonResp);
	}
	
	static protected JsonRequest buildJsonRequest(JsonNode json, ObjectMapper jsonMapper) {
		JsonRequest jsonReq = new JsonRequest();
		jsonReq.setSeq(json.get("seq").getLongValue());
		jsonReq.setClientTime(json.get("clientTime").getLongValue());
		jsonReq.setUserAgent(json.get("userAgent").getTextValue());
		
		JsonNode calls = json.get("calls");
		List<JsonCall> jcls = new ArrayList<JsonCall>(calls.size());
		for(JsonNode call : calls) {
			JsonCall jcall = new JsonCall();
			jcall.setMethod(call.get("method").getTextValue());
			jcall.setData(call.get("data"));
			jcall.setIdx(call.get("idx").getLongValue());
			jcls.add(jcall);
		}
		jsonReq.setCalls(jcls);
		return jsonReq;
	}

	public JsonRequestWaiter getJsonRequestWaiter() {
		return jsonRequestWaiter;
	}

	public void setJsonRequestWaiter(JsonRequestWaiter jsonRequestWaiter) {
		this.jsonRequestWaiter = jsonRequestWaiter;
	}
}
